﻿#include <fstream>
#include <ctype.h>
#include<cmath>
#include<map>
#include<list>
//#include <py_api/py_runner.h>

#include <thread>         // std::this_thread::sleep_for
#include <chrono>
#include <cppbase/utility.h>
#include "file_base.h"
#include "file_store.h"
namespace fs = std::filesystem;
FileStoreBase::FileStoreBase( std::string rootpath):dir(rootpath)
{
}

bool FileStoreBase::check_file_valid(fs::path f)
{
	if (!fs::exists(f)) {
		if (!fs::exists(append_tmp(f))) {
			//LOG(WARNING) <<"read unexist file:" + f.string();
			return false;
		}
		else
		{
			int i = 10;
			for (; i > 0; --i) {
				std::this_thread::sleep_for(std::chrono::milliseconds(100));
				if (fs::exists(f))
					return true;
			}
			if (i == 0) {
				//LOG(ERROR) << "tmp file locked too long:"<<append_tmp(f).string();
				return false;
			}
		}
	}
	return true;
}
uint32_t FileStoreBase::today()
{
	time_t now = std::time(0) ;
	// returned value is static, No NEED free it.
	tm* ltm = std::localtime(&now);
	uint32_t day = (ltm->tm_year + 1900) * 10000 + (ltm->tm_mon + 1) * 100 + ltm->tm_mday;
	return day;
}
std::vector<char> FileStoreBase::read_bytes(Exchange exchangeid, std::string symbol, BarSize barsize)
{
	auto v=std::vector<char>();
	auto f = get_filepath(exchangeid,symbol,barsize);
    
	if(!check_file_valid(f))
		return v;
	
	std::ifstream file;
	file.open(f, std::ios::binary | std::ios::in);
	file.seekg(0, std::ios_base::end);
	int size = file.tellg();
	v.resize(size);
	file.seekg(0, std::ios_base::beg);
	file.read((char*)(v.data()),size);
	file.close();
	return v;
}

std::vector<char> FileStoreBase::read_bytes(fs::path f)
{
	auto v = std::vector<char>();

	if (!fs::exists(f)) {
		std::cout << "file not exist:" + f.string()<<std::endl;
		return v;
	}

	std::ifstream file;
	file.open(f, std::ios::binary | std::ios::in);
	file.seekg(0, std::ios_base::end);
	int size = file.tellg();
	v.resize(size);
	file.seekg(0, std::ios_base::beg);
	file.read((char*)(v.data()), size);
	file.close();
	return v;
}

void FileStoreBase::read_partial_bytes(fs::path f, int start, int length, char* buf)
{
	if (!check_file_valid(f))
		return;
	std::vector<char> v;
	std::ifstream file;
	file.open(f, std::ios::binary | std::ios::in);
	file.seekg(start, std::ios_base::beg);
	file.read(buf, length);
	file.close();
	return ;

}

